package controller

import (
	"encoding/json"
	"log"
	"myapp/model"
	"net/http"
	"strconv"
	"time"
)

func registerCustomer() {
	http.HandleFunc("/customer/index", getMany)
	http.HandleFunc("/customer/details", getOne)
	http.HandleFunc("/customer/create", Add)
}

func Add(w http.ResponseWriter, r *http.Request) {

	c := &model.Customer{
		FirstName:  "你",
		LastName:   "可真丑",
		Address1:   "山西省长治市",
		Address2:   "天津市河西区",
		Provine:    "山西省",
		City:       "长治市",
		Created_at: time.Now(),
		Updated_at: time.Now(),
	}

	_ = c.Add()

}

func getOne(w http.ResponseWriter, r *http.Request) {

	c := &model.Customer{}

	switch r.Method {

	case "get", "GET":

		r.ParseForm()
		id, err := strconv.Atoi(r.Form.Get("id"))

		if err != nil {
			log.Fatalln("无法将 url ID 参数转为 int 类型")
		}

		c.Id = uint(id)
		c = c.GetOne()

		jc, _ := json.Marshal(c)
		w.Write([]byte(string(jc)))
	}
}

func getMany(w http.ResponseWriter, r *http.Request) {

	c := &model.Customer{}

	switch r.Method {
	case "get", "GET":
		r.ParseForm()

		if ok := r.Form.Has("limit"); ok {
			limit, _ := strconv.Atoi(r.Form.Get("limit"))
			c.Limit = uint(limit)
		}
		if ok := r.Form.Has("offset"); ok {
			offset, _ := strconv.Atoi(r.Form.Get("offset"))
			c.Offset = uint(offset)
		}

		cc := c.GetMany()

		p := &model.PageData{}
		p1 := p.New(&c.PageInstance)
		jp, _ := json.Marshal(p1)
		// 遵循 rest ful 风格 将分页信息放在响应的header
		w.Header().Set("PageInstance", string(jp))

		jc, _ := json.Marshal(cc)
		w.Write([]byte(string(jc)))

	}

}
